<?php

namespace App\Http\Controllers\web;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserList;
use App\Http\Requests\UserLoginCheck;
use App\Http\Requests\UserRegist;
use App\Http\Service\UserInterface;
use Mews\Captcha\Facades\Captcha;

class UserController extends Controller
{

    public $user;

    public function __construct(UserInterface $user)
    {
        $this->user = $user;
    }

    public function weChat()
    {
        define("TOKEN", "weixin");//修改为服务器配置里的Token值“qiezijiang123”
        $this->valid();
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];//获取GET请求中的参数"signature"
        $timestamp = $_GET["timestamp"];//获取GET请求中的参数"timestamp"
        $nonce = $_GET["nonce"];        //获取GET请求中的参数"nonce"

        $token = TOKEN;//将代码中我们定义的TOKEN赋值给token
        $tmpArr = array($token, $timestamp, $nonce);//将以上三个参数放进数组
        sort($tmpArr, SORT_STRING);//将数组的元素当做字符串来处理，并按升序排序
        $tmpStr = implode( $tmpArr );//将排序好的数组元素重新组合成一个字符串
        $tmpStr = sha1( $tmpStr );//进行sha1加密

        if( $tmpStr == $signature ){//将组合的字符串和微信服务器传过来的参数"signature"进行对比
            return true;
        }else{
            return false;
        }
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;//校验成功，返回随机字符串
            exit;
        }
    }

    public function getOpenID()
    {
        $app = \EasyWeChat::officialAccount();
        $user = session('wechat.oauth_user.default');  //获取微信用户信息
        $openID = $user->getId();          //获取openID
        dd($openID);
    }

    public function getCaptcha()
    {
        return Captcha::create('flat');
    }

    public function login(UserLoginCheck $request)
    {
        $data = $request->only('username','password');
        return $this->user->login($data);
    }

    public function register()
    {
        return view('User.Login.regist');
    }

    public function regist(UserRegist $request)
    {
        $data = $request->all();
        return $this->user->regist($data);
    }

    public function homePage()
    {
        return view('User.Home.index');
    }

    public function getList()
    {
        return view('User.Home.userList');
    }

    public function userList(UserList $request)
    {
        $data = $request->all();
        return $this->user->getList($data);
    }
}